package com.qf.xiaomi.web.servlet;

import com.qf.xiaomi.pojo.TbCart;
import com.qf.xiaomi.pojo.TbCartList;
import com.qf.xiaomi.pojo.TbUser;
import com.qf.xiaomi.service.cartService;
import com.qf.xiaomi.service.impl.cartServiceImpl;
import com.qf.xiaomi.utils.StringConstans;
import com.qf.xiaomi.utils.StringUtils;
import com.qf.xiaomi.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/cart")
public class CartServlet extends BaseServlet {
    cartService service=new cartServiceImpl();
    public String create(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("id");
        if (StringUtils.isEmpty(id)){
            return StringConstans.REDIRECT+"/index.jsp";
        }
        long goodId = Long.parseLong(id);
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        if (user==null){
            return StringConstans.REDIRECT+"/index.jsp";
        }
        long userId = user.getId();
        service.addCart(userId,goodId);
        req.setAttribute("user",user);
        return StringConstans.FORWARD+"/cartSuccess.jsp";
    }
    public String show(HttpServletRequest req,HttpServletResponse resp){
//        String uidStr = req.getParameter("uid");
//        if (StringUtils.isEmpty(uidStr)){
//            return StringConstans.REDIRECT+"/index.jsp";
//        }
//        long uid = Long.parseLong(uidStr);
        TbUser user = (TbUser) req.getSession().getAttribute("user");
        long uid=user.getId();
        TbCartList tbCartList = new TbCartList();
        TbCartList cart = service.selectByUid(uid, tbCartList);
        req.getSession().setAttribute("cart",cart);
        return StringConstans.REDIRECT+"/cart.jsp";
    }
    public String delete(HttpServletRequest req,HttpServletResponse resp){
        String cidStr = req.getParameter("cid");
        if (StringUtils.isEmpty(cidStr)){
            return StringConstans.REDIRECT+"/index.jsp";
        }
        long cid = Long.parseLong(cidStr);
        service.del(cid);
        return StringConstans.REDIRECT+"/cart?method=show";
    }
    public String clear(HttpServletRequest req,HttpServletResponse resp){
        int clearA = service.clearCart();
//        if (clearA>0) {
            return StringConstans.REDIRECT+"/cart?method=show";
//        }else {
//            req.setAttribute("exp","清空失败");
//            return StringConstans.FORWARD+"/error/error.jsp";
//        }
    }
}
